<template>
  <div class="user-profile-container">
    <el-card class="profile-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2><el-icon><User /></el-icon> 个人信息修改</h2>
        </div>
      </template>

      <div class="profile-content">
        <!-- 左侧头像区域 -->
        <div class="avatar-section">
          <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8081/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
          >
            <div class="avatar-wrapper">
              <img v-if="form.dto.avatar" :src="form.dto.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Avatar /></el-icon>
              <div class="avatar-mask">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>

          </el-upload>
          <div class="avatar-hint">
            <span class="hint">支持 JPG/PNG 格式，大小不超过 10MB</span>
          </div>
        </div>

        <!-- 右侧表单区域 -->
        <div class="form-section">
          <el-form
              ref="formRef"
              :model="form.dto"
              :rules="rules"
              label-width="100px"
              label-position="left"
          >
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="form.dto.userId" disabled>
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.dto.username" disabled>
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="form.dto.nickName" placeholder="请输入昵称">
                <template #prefix>
                  <el-icon><Edit /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.dto.phone" placeholder="请输入手机号">
                <template #prefix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <!-- <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.dto.email" placeholder="请输入邮箱">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item> -->

            <el-form-item label="收货地址" prop="email">
              <el-input v-model="form.dto.email" placeholder="请输入收获地址">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">
                <el-icon><Check /></el-icon> 保存修改
              </el-button>
              <el-button @click="resetForm">
                <el-icon><Refresh /></el-icon> 重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import {
  User, Avatar, Camera, Edit, Iphone, Message, Check, Refresh
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from "axios";

// 为 el-upload 组件准备请求头
const uploadHeaders = computed(() => {
  return {
    token: sessionStorage.getItem('token') || ''
  }
})

// 表单数据
const form = reactive({
  dto: {
    userId: null,
    username: '',
    nickName: '',
    phone: '',
    email: '',
    avatar: ''
  }
})

// 表单验证规则
const rules = reactive({
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

const formRef = ref(null)

// 头像上传成功处理
const handleAvatarSuccess = (response) => {
  // 假设后端返回 { code: 200, data: '图片URL' } 格式
  if (response && response.data && response.code === 200) {
    form.dto.avatar = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 10MB!')
  }

  return isImage && isLt2M
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const token = sessionStorage.getItem('token');
      if (!token) {
        ElMessage.warning('请先登录');
        return;
      }
      try {
        // 全局拦截器已修复，使用标准 axios 写法
        const res = await axios.post('/updateUserInfo', form.dto);
        // 拦截器会处理非200的情况，能走到这里说明 code 就是 200
        ElMessage.success(res.data || '个人信息更新成功');
        loadUserInfo(); // 更新成功后重新加载用户信息
      } catch (error) {
        // 错误已由拦截器统一弹出提示，这里只需在控制台记录
        console.error("更新用户信息失败:", error);
      }
    }
  })
}


// 重置表单
const resetForm = () => {
  // 重置表单验证状态和数据
  if (!formRef.value) return
  formRef.value.resetFields()
  // 重新加载原始用户信息
  loadUserInfo()
}

// 加载用户信息
const loadUserInfo = async () => {
  const token = sessionStorage.getItem('token');
  if (!token) {
    ElMessage.warning('尚未登录，无法获取用户信息');
    return;
  }
  try {
    // 全局拦截器已修复，使用标准 axios 写法
    const res = await axios.post('/userInfo');
    // 拦截器会处理非200的情况，能走到这里说明 res.code 就是 200
    // 并且拦截器已经帮我们返回了 res.data，所以直接用 res.data
    form.dto = res.data;
  } catch (error) {
    // 错误已由拦截器统一弹出提示，这里只需在控制台记录
    console.error("获取用户信息失败:", error);
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.user-profile-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.profile-card {
  border-radius: 12px;
  border: none;
  background-color: #f8fafc;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #2d3748;
  font-weight: 600;
}

.profile-content {
  display: flex;
  gap: 40px;
}

.avatar-section {
  width: 250px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form-section {
  flex: 1;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.avatar-wrapper {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.avatar-uploader-icon {
  font-size: 40px;
  color: #cbd5e1;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f1f5f9;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-mask .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.avatar-hint {
  margin-top: 16px;
  text-align: center;
}

.avatar-hint .hint {
  font-size: 12px;
  color: #64748b;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-button {
  padding: 10px 20px;
  border-radius: 8px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.el-button--primary {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

.el-button--primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
  }

  .avatar-section {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>